package pri.ydy.msmservice.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import pri.ydy.commonUtils.R;
import pri.ydy.msmservice.service.MsmService;
import pri.ydy.msmservice.utils.RandomUtil;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author YeDongYong
 * @date 2020/12/16 - 16:44
 */
@RestController
@RequestMapping("/edumsm/msm")
public class MsmApiController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String,String > redisTemplate; //redis模板

    //发送短信的方法
    @GetMapping("send/{phone}")
    public R sendMsm(@PathVariable String phone){
        //1.从Redis里获取验证码，能获得就返回
        String code = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)){
            return R.ok();
        }
        //2.没有获得，则进行阿里云发送
        //生成随机验证码
        code= RandomUtil.getFourBitRandom();
        Map<String,Object> param=new HashMap<>();
        param.put("code",code);
        //调用service进行短信发送
        boolean isSend= msmService.sendMsm(param,phone);
        if ((isSend)){
            //发送成功，将验证码存到Redis里，设置有效时间。
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return R.ok();
        }
        else return R.error().message("短信发送失败");
    }


}
